package com.friends.utils.id;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * 规则id生成工具
 *
 * @author dark
 * @since 2023-03-15
 */
@Service
public class IdGeneratorService {
    private static final String PREFIX = "REDIS PREFIX";
    private static final int DIGIT_COUNT = 4;
    private static final String PATTERN = "ID PREFIX" + "%s%0" + DIGIT_COUNT + "d";

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    
    /**
     * 生成规则id (当前规则:ID PREFIX + 20230629 + 0001)
     * @return 出库id
     */
    public String generateId() {
        String today = DateFormatThreadLocal.getDateFormat().format(new Date());
        DateFormatThreadLocal.remove();
        String key = PREFIX + today;
        Long code = stringRedisTemplate.opsForValue().increment(key);
        if (Objects.equals(code, 1L)) {
            stringRedisTemplate.expire(key, 1, TimeUnit.DAYS);
        }
        return String.format(PATTERN, today, code);
    }
}
